package com.happy3w.cmds.maven;

import com.beust.jcommander.Parameter;
import com.happy3w.cmds.command.ArgAppCmd;
import com.happy3w.cmds.command.NoneSplitter;
import com.happy3w.cmds.component.output.ConsoleTextOutput;
import com.happy3w.cmds.component.output.FileTextOutput;
import com.happy3w.cmds.component.output.TextOutput;
import com.happy3w.cmds.maven.mermaid.MermaidDrawer;
import com.happy3w.cmds.maven.model.JavaModule;
import com.happy3w.cmds.maven.model.JavaModuleDictionary;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ShowModuleDependsCmd extends ArgAppCmd<ShowModuleDependsCmd.Args> {

    protected ShowModuleDependsCmd() {
        super(ShowModuleDependsCmd.Args.class);
    }

    @Override
    public String getName() {
        return "show-module-depends";
    }

    @Getter
    @Setter
    public static class Args {
        @Parameter(names = {"-i", "--in"}, description = "root project dirs", required = true, splitter = NoneSplitter.class)
        private List<String> projectDirs = new ArrayList<>();

        @Parameter(names = {"-o", "--output"}, description = "output file")
        private String outputFile;
    }

    @Override
    public void runWithArg(Args args) throws Exception {
        TextOutput output = args.outputFile != null ? new FileTextOutput(args.outputFile) : new ConsoleTextOutput();
        try {
            List<JavaModule> parentModules = args.projectDirs.stream()
                    .map(JavaModule::extract)
                    .toList();
            JavaModuleDictionary dictionary = JavaModuleDictionary.from(parentModules);

            MermaidDrawer drawer = new MermaidDrawer(dictionary, GraphOption.builder()
                    .showGroup(true)
                    .showGroup(false)
                    .build());
            drawer.draw(output);
        } finally {
            output.close();
        }
    }
}
